package com.scpii.universal.resource;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.scpii.universal.pb.UniversalProtocol.Cmd;
import com.scpii.universal.pb.UniversalProtocol.GetPackInfoCS;
import com.scpii.universal.service.PbInterfaceService;
import com.scpii.universal.util.CacheUtil;
import com.scpii.universal.util.Conversion;
import com.scpii.universal.util.StreamUtil;

@Path("rest")
@Component
public class DataQueryResource {
	private static final Logger log = LoggerFactory
			.getLogger(DataQueryResource.class);
	@Resource
	private PbInterfaceService pbInterfaceService;
	
	private static final Response noContent = Response.noContent().build();
	@Context
	HttpServletRequest request;

	/*
	 * 以GET方法请求
	 */
	@GET
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public Response getData(@QueryParam("cmd") Integer cmd,
			@QueryParam("data") String data) {

		Response resp;
		try {
			if (cmd == null) {
				return noContent;
			}
			byte[] reqData = data != null && data.length() > 0 ? Conversion
					.hexStringToBytes(data) : null;
			resp = dealData(cmd, reqData);

		} catch (Exception e) {
			resp = noContent;
			e.printStackTrace();
		}

		return resp;
	}

	/*
	 * 以POST方法请求
	 */
	@POST
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public Response getDataPost(@QueryParam("cmd") Integer cmd)
			throws Exception {

		Response resp;
		try {
			if (cmd == null)
				return noContent;

			byte[] reqData = StreamUtil
					.convertToBytes(request.getInputStream());
			resp = dealData(cmd,
					reqData != null && reqData.length > 0 ? reqData : null);
		} catch (Exception e) {
			resp = noContent;
			e.printStackTrace();
		}

		return resp;
	}

	private final Response dealData(int cmd, byte[] data) throws Exception {
		byte[] content = null;
		log.info("cachekey" + CacheUtil.getCachekey(cmd, data));
		switch (Cmd.valueOf(cmd)) {
		case GetPackInfo:// 查询打包信息
			log.info("查询打包信息开始");
			GetPackInfoCS getPackInfoCS = GetPackInfoCS.parseFrom(data);
			int appUpdateId = getPackInfoCS.getAppUpdateId();
			log.info("appUpdateId:" + appUpdateId);
			content = pbInterfaceService.getPackInfoService(appUpdateId);
			log.info("查询打包信息结束");
			break;
		default:
			break;
		}
		Response resp;
		if (content == null) {
			resp = noContent;
		} else {
			resp = Response
					.ok(content, MediaType.APPLICATION_OCTET_STREAM_TYPE)
					.build();
		}

		return resp;
	}
}
